package cn.picclife.mwx.manager.sys.service.impl;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.picclife.mwx.common.core.util.crypto.DESUtils;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainVersionMapper;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.SysMaintainReq;
import cn.picclife.mwx.manager.sys.model.po.SysMaintain;
import cn.picclife.mwx.manager.sys.model.po.SysmaintainVersion;
import cn.picclife.mwx.manager.sys.service.SysMaintainVersionService;

@Service
public class SysMaintainVersionServiceImpl implements SysMaintainVersionService{

	private static final Log log = LogFactory.getLog(SysMaintainVersionServiceImpl.class);

	@Autowired
	private SysMaintainVersionMapper sysMaintainVersionMapper;
	
	@Autowired
	private SysMaintainMapper sysMaintainMapper;
	@Value("${file.filedir}")
	private String fileDir;	
	/**
	 * 保存信息
	 * @throws Exception 
	 */
	public void saveSysMaintain(SysMaintainReq req) throws Exception {
		
		SysmaintainVersion maintain = new SysmaintainVersion();
		maintain.setSysversionId(UUID.randomUUID().toString());
		maintain.setSysmaintainId(req.getId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(null!=req.getVersionUpdateTime()&&req.getVersionUpdateTime().trim().length()>0) {
			maintain.setVersionUpdateTime(sdf.parse(req.getVersionUpdateTime()));
		}
		MultipartFile file = req.getUploadFile();
		String localPath = "";
		if(file!=null) {
			log.info("============="+JSONObject.toJSON(file).toString());
			log.info("文件上传开始：");
			String fileName = file.getOriginalFilename();
			StringBuffer localFileName = new StringBuffer();
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
			String str = sdf1.format(new Date());//为文件加后缀
			
			if(null!=fileName&&fileName.trim().length()>0) {
				String[] nameStr = fileName.split("\\.");
				if(nameStr!=null&&nameStr.length>0) {
					localFileName.append(nameStr[0]).append(str).append(".").append(nameStr[1]);
				}
			}
			maintain.setFileName(localFileName.toString());//文件名
			String systemName = req.getSystemName();
			if(req.getSystemName()==null||req.getSystemName().trim().length()<=0) {
				 systemName = UUID.randomUUID().toString();
			}
			localPath = fileDir+systemName;//本地文件路径:文件路径+服务器名
			File localUrlFile = new File(localPath);
			//如果文件夹不存在则新建
	        if(!localUrlFile.exists()) {
	        	localUrlFile.mkdirs();
	        }
			if(localFileName.toString().trim().length()<=0) {
				localFileName.append(fileName);
			}
			File newFile = new File(localPath + "/" + localFileName.toString());
			
//			File newFile = new File("D:\\wenjian\\666666");
			// 将内存中的数据写入磁盘
	        try {
				file.transferTo(newFile);
			} catch (IllegalStateException e) {
				log.error("异常信息："+e.getMessage(),e);
			} catch (IOException e) {
				log.error("异常信息："+e.getMessage(),e);
			}
			log.info("文件上传成功！");
		}else {
			SysMaintain main = new SysMaintain();
			main.setId(req.getId());
			List<SysMaintain>list = sysMaintainMapper.querySysMaintain(main);
			if(list!=null&&"1".equals(list.get(0).getAutoFlag())) {
				main =  list.get(0);
				req.setServerConStr(main.getServerConStr());//服务器连接串
				req.setFileName(main.getFileName());//项目服务器文件名
				req.setFileUrl(main.getFileUrl());//项目服务器目录
				req.setPassword(main.getPassword());//密码
				//ftpDownload(req);
			}
		}
		maintain.setVersionNo(req.getVersionNo());
		maintain.setVersionUrl(localPath);
		sysMaintainVersionMapper.saveSysMaintainVersion(maintain);
	}
	
	/**
	 * 查询数据
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public PageCount querySysMaintainVersionPage(SysMaintainReq req) throws Exception {
		
		
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(req.getNowPage());//当前页
		pageCount.setRowNum(req.getRowNum());//每页多少条
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("sysmaintainId", req.getId());//系统编码
		int allCount = sysMaintainVersionMapper.queryAllCount(paramMap);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}

		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(paramMap);
		List<SysmaintainVersion> sysMaintainVersionList = sysMaintainVersionMapper.querySysMaintainVersionPage(pageCount);
		pageCount.setDatas(sysMaintainVersionList);
		return pageCount;
	}
	
	/**
	 * 更新
	 * @param req
	 * @return
	 * @throws ParseException 
	 */
	public int updateSysMaintain(SysMaintainReq req) throws ParseException {
		
		SysmaintainVersion maintain = new SysmaintainVersion();
		maintain.setSysmaintainId(req.getId());
		maintain.setSysversionId(req.getSysversionId());
		List list = sysMaintainVersionMapper.querySysMaintainVersion(maintain);
		if(null==list||list.size()<=0) {
			return 2;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(null!=req.getVersionUpdateTime()&&req.getVersionUpdateTime().trim().length()>0) {
			maintain.setVersionUpdateTime(sdf.parse(req.getVersionUpdateTime()));
		}
		MultipartFile file = req.getUploadFile();
		String localPath = "";
		//如果上传文件不为空则下载上传文件，如果上传文件为空则判断是否自动下载，若是自动线下载则ftp下载
		if(file!=null) {
			log.info("============="+JSONObject.toJSON(file).toString());
			log.info("文件上传开始：");
			String fileName = file.getOriginalFilename();
			StringBuffer localFileName = new StringBuffer();
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String str = sdf2.format(new Date());//为文件名加时间后缀
			if(null!=fileName&&fileName.trim().length()>0) {
				String[] nameStr = fileName.split("\\.");
				if(nameStr!=null&&nameStr.length>0) {
					localFileName.append(nameStr[0]).append(str).append(".").append(nameStr[1]);
				}
			}
			maintain.setFileName(localFileName.toString());//文件名
			String systemName = req.getSystemName();
			if(req.getSystemName()==null||req.getSystemName().trim().length()<=0) {
				 systemName = UUID.randomUUID().toString();
			}
			localPath = fileDir+systemName;//本地文件路径:文件路径+服务器名
			maintain.setVersionUrl(localPath);//文件上传路径
			File localUrlFile = new File(localPath);
			//如果文件夹不存在则新建
	        if(!localUrlFile.exists()) {
	        	localUrlFile.mkdirs();
	        }
	        if(localFileName.toString().trim().length()<=0) {
				localFileName.append(fileName);
			}
			File newFile = new File(localPath + "/" + localFileName.toString());
			log.info("====文件手动上传路径==="+newFile);
//			File newFile = new File("D:\\wenjian\\666666");
			// 将内存中的数据写入磁盘
	        try {
				file.transferTo(newFile);
			} catch (IllegalStateException e) {
				log.error("异常信息："+e.getMessage(),e);
			} catch (IOException e) {
				log.error("异常信息："+e.getMessage(),e);
			}
			log.info("文件上传成功！");
		}else {
			SysMaintain main = new SysMaintain();
			main.setId(req.getId());
			List<SysMaintain>mainlist = sysMaintainMapper.querySysMaintain(main);
			if(list!=null&&"1".equals(mainlist.get(0).getAutoFlag())) {
				main =  mainlist.get(0);
				req.setServerConStr(main.getServerConStr());//服务器连接串
				req.setFileName(main.getFileName());//项目服务器文件名
				req.setFileUrl(main.getFileUrl());//项目服务器目录
				req.setPassword(main.getPassword());//密码
				//ftpDownload(req);
			}
		}
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(null!=req.getVersionUpdateTime()&&req.getVersionUpdateTime().trim().length()>0) {
			maintain.setVersionUpdateTime(sdf1.parse(req.getVersionUpdateTime()));
		}
		maintain.setVersionNo(req.getVersionNo());
		int a =  sysMaintainVersionMapper.updateSysMaintainVersion(maintain);
		return a;
	}

	/**
	 * 查询数据
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public List<SysmaintainVersion> querySysMaintain(SysMaintainReq req) throws Exception {
		
		SysmaintainVersion maintain = new SysmaintainVersion();
		maintain.setSysmaintainId(req.getId());
		maintain.setFileName(req.getUploadFile().getName());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(null!=req.getVersionUpdateTime()&&req.getVersionUpdateTime().trim().length()>0) {
			maintain.setVersionUpdateTime(sdf.parse(req.getVersionUpdateTime()));
		}
		maintain.setVersionNo(req.getVersionNo());
		maintain.setVersionUrl(req.getVersionUrl());
		return  sysMaintainVersionMapper.querySysMaintainVersion(maintain);
	}
	
	/**
	 * ftp服务器文件下载
	 */
//	public void ftpDownload(SysMaintainReq req) {
//		
//		/*String userName = "ftpadmin";//ftp服务器的用户名
//		String ip = "192.168.1.199";// ftp服务器的ip地址
//		int ports = 21;// ftp服务器的端口号
//		String passWord = "123456";// ftp服务器的密码
//		String ftpFileUrl="/home/ftpadmin";//ftp文件地址
//		String localPath = "D:\\wenjian";//本地文件路径
//		String fileName = "wwww.zip";*/
//		String serverConStr = req.getServerConStr();//服务器连接串 user@ip:port
//		String[] serv = serverConStr.split("@");
//		String[] ip_port = serv[1].split(":");
//		String userName = serv[0];
//		String ip = ip_port[0];
//		int port = Integer.valueOf(ip_port[1]);
//		char[] passWord = req.getPassword();
//		String ftpFileUrl=req.getFileUrl();//ftp文件地址
//		String fileName = req.getFileName();
//		String sysName = req.getSystemName();
//		if(req.getSystemName()==null||req.getSystemName().trim().length()<=0) {
//			sysName = UUID.randomUUID().toString();
//		}
//		String localPath = ResponseStatusEnum.FTP_FILE_URL.getName()+sysName;//本地文件路径:文件路径+服务器名
//		File file = new File(localPath);
//        //如果文件夹不存在则新建
//        if(!file.exists()) {
//        	file.mkdirs();
//        }
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
//		String str = sdf.format(new Date());//为文件加后缀
//		
//		StringBuffer localFileName = new StringBuffer();
//		if(null!=fileName&&fileName.trim().length()>0) {
//			String[] nameStr = fileName.split(".");
//			if(nameStr!=null&&nameStr.length>0) {
//				localFileName.append(nameStr[0]).append(str).append(".").append(nameStr[1]);
//			}
//		}
//		boolean a = FtpFileUtil.retrieveFile(ip, port, userName, passWord, ftpFileUrl, fileName, localPath,localFileName.toString());
//		log.info("==========ftp下载结果=="+a);
//		
//	}
	
	
//	public boolean ftpConnect(SysMaintainReq req) throws Exception {
//		
//		String serverConStr = req.getServerConStr();//服务器连接串 user@ip:port
//		String[] serv = serverConStr.split("@");
//		String[] ip_port = serv[1].split(":");
//		String userName = serv[0];
//		String ip = ip_port[0];
//		int port = Integer.valueOf(ip_port[1]);
//		String passWord = req.getPassword();
//		return FtpFileUtil.ftpConnect(ip, port, userName, passWord);
//	}

//	public static void ftpDownload1() {
////		String userName = "tianqiftp";//ftp服务器的用户名
////		String ip = "9.23.24.170";// ftp服务器的ip地址
////		int ports = 21;// ftp服务器的端口号
////		String passWord = "e05Con25Omy";// ftp服务器的密码
//		String userName = "ftpadmin";//ftp服务器的用户名
//		String ip = "192.168.1.199";// ftp服务器的ip地址
//		int ports = 21;// ftp服务器的端口号
//		String passWord = "123456";// ftp服务器的密码
//		String ftpFileUrl="/home/ftpadmin";//ftp文件地址
//		String localPath = "D:\\wenjian";//本地文件路径
//		String fileName = "wwww.zip";
//		boolean a = false;
//		a = FtpFileUtil.retrieveFile(ip, ports, userName, passWord, ftpFileUrl, fileName, localPath,null);
//		log.info("ftp下载结果"+a);
//		
//		SysmaintainVersion maintainVersion = new SysmaintainVersion();
////		sysMaintainVersionMapper.querySysMaintainVersion(maintain)
////		sysMaintainVersionMapper.saveSysMaintainVersion(maintain);
//	}
	
	public static void main(String[] args) {
//		ftpDownload1();
	}

}
